require 'daemons'
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))

Daemons.run_proc('powerdaemon', :backtrace => true) do
  logger = ActiveSupport::BufferedLogger.new(
    File.join(Rails.root, "log", "powerdaemon.log"),Logger::INFO)
  Rails.logger = logger
  ActiveRecord::Base.logger = logger
  ilms = SerialInterface.new
  s = UtilityFunctions.current_interval/10
  
  loop do
    power = ilms.read_power[0]
    green = GreenSimulation.get_green_power
    net = power-green
    dollars = net*UtilitySetting.get_price
    prev = PowerLog.last
    t = UtilityFunctions.current_time[0]
    if  UtilitySetting.is_peak
    	net_peak = prev.net_peak + net
    	net_off_peak = prev.net_off_peak
    else
    	net_peak = prev.net_peak
    	net_off_peak = prev.net_off_peak + net
    end
    power_update = PowerLog.create(
       :loadbox_id => 1,
       :logged_at  => Time.local(2012,nil,nil,t[0],t[1]),
       :power_consumption => power,
       :ppv => green,
       :pgrid => net,
       :net_dollars => dollars,
       :net_peak => net_peak,
       :net_off_peak => net_off_peak)
    logger.info "#{power_update.power_consumption} Kw, #{power_update.net_peak}"
    sleep(3)
  end
end

